#include <stdio.h>
#include <stdlib.h>

#define MAX_N 1000
#define MAX_M 1000

const int dx[] = { -1, 1, 0, 0 };
const int dy[] = { 0, 0, -1, 1 };

typedef struct 
{
    int x, y;
} Point;

typedef struct
{
    Point data[MAX_N * MAX_M];
    int front, rear;
} Queue;

void initQueue(Queue* q) 
{
    q->front = q->rear = 0;
}

int isEmpty(Queue* q)
{
    return q->front == q->rear;
}

void enqueue(Queue* q, Point p) 
{
    q->data[q->rear++] = p;
}

Point dequeue(Queue* q) 
{
    return q->data[q->front++];
}

int main()
{
    int n, m;
    int xs, ys, xt, yt;
    char grid[MAX_N][MAX_M + 1]; 
    int dist[MAX_N][MAX_M];

    if (scanf_s("%d %d", &n, &m) != 2)
    {
        printf("-1\n");
        return 0;
    }

    if (scanf_s("%d %d %d %d", &xs, &ys, &xt, &yt) != 4)
    {
        printf("-1\n");
        return 0;
    }
    xs--; ys--; xt--; yt--; 

    for (int i = 0; i < n; i++)
    {
        if (scanf_s("%s", grid[i]) != 1)
        {
            printf("-1\n");
            return 0;
        }
    }

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            dist[i][j] = -1; 
        }
    }

    Queue q;
    initQueue(&q);

    Point start = { xs, ys };
    dist[xs][ys] = 0;
    enqueue(&q, start);

    while (!isEmpty(&q))
    {
        Point current = dequeue(&q);
        int x = current.x;
        int y = current.y;

        if (x == xt && y == yt)
        {
            break;
        }

        for (int i = 0; i < 4; i++) 
        {
            int nx = x + dx[i];
            int ny = y + dy[i];

            if (nx >= 0 && nx < n && ny >= 0 && ny < m)
            {
                if (grid[nx][ny] == '.' && dist[nx][ny] == -1)
                {
                    dist[nx][ny] = dist[x][y] + 1;
                    Point next = { nx, ny };
                    enqueue(&q, next);
                }
            }
        }
    }
    printf("%d\n", dist[xt][yt]);

    return 0;
}